<template>
  <el-card style="margin-top: 15px">
    <div>
      <div class="one-button">
        <el-upload class="upload-demo"
                   :action="uploadUrl2"
                   :before-upload="importOpt"
                   :on-error="handleUploadError"
                   :before-remove="beforeRemove"
                   multiple
                   :limit="1"
                   :on-exceed="handleExceed"
                   accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                   :file-list="fileList">
          <el-button size="small" type="primary"><i class="el-icon-upload2 el-icon--left"></i>{{titleName.importName}}</el-button>
        </el-upload>
      </div>
      <div class="one-button">
        <el-button size="small" type="primary" @click="exportOpt"><i class="el-icon-download el-icon--left"></i>{{titleName.exportName}}</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: "IEButton",
  props: ['titleName'],
  data() {
    return {
    }
  },
  methods: {
    importOpt(file) {
      var that = this
      this.fileTemp = file
      let fileName = file.name
      let fileType = fileName.substring(fileName.lastIndexOf('.') + 1);
      // 判断上传文件格式
      if (this.fileTemp) {
        if ((fileType != 'xlsx') && (fileType != 'xls')) {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
          return;
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
        return;
      }
      this.uploadUrl = this.$conf.baseURL + '/uploadExcel'
      let formData = new FormData();
      formData.append("mfile", file);
      this.$http({
        method: 'post',
        url: that.uploadUrl,
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then((res) => {
        if (res.data.code === 200) {
          that.$message({
            type: 'success',
            message: '导入成功'
          })
          that.$parent.initTree()
        } else {
          that.$message({
            type: 'error',
            message: '文件格式错误,导入失败'
          })
        }
      }).catch(error => {
        that.$message({
          type: 'error',
          message: '文件格式错误'
        })
      })
    }
  }
}
</script>

<style scoped>
.one-button {
  float: left;
  width: 117px;
  height: 50px;
}
</style>
